package com.jctrip.hotel.source.xxl.rezen.thread;

import com.jctrip.hotel.common.constant.RedisKeyConstant;
import com.jctrip.hotel.common.context.BeanContext;
import com.jctrip.hotel.common.util.JsonUtil;
import com.jctrip.hotel.common.util.RedisUtil;
import com.jctrip.hotel.domain.entity.HtSourceInfo;
import com.jctrip.hotel.source.service.rezen.RezenService;
import com.jctrip.hotel.source.service.rezen.RezenTaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.time.DateUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Author：Haruhi
 * @description:
 * @Date：2023/9/26 20:19
 * @Package：com.jctrip.hotel.source.xxl.rezen.thread
 * @Project：hotel-main
 */
@Slf4j
public class SyncRezencoRatesTaskThread implements Runnable{
    private final List<HtSourceInfo> sourceInfos;
    private final Integer days;


    public SyncRezencoRatesTaskThread(List<HtSourceInfo> sourceInfos, Integer days) {
        this.sourceInfos = sourceInfos;
        this.days = days;
    }

    @Override
    public void run() {
        RedisUtil redisUtil = BeanContext.getApplicationContext().getBean(RedisUtil.class);
        RezenTaskService rezenTaskService = BeanContext.getApplicationContext().getBean(RezenTaskService.class);
        RezenService rezenService = BeanContext.getApplicationContext().getBean(RezenService.class);

        while (redisUtil.lGetListSize(RedisKeyConstant.HOTEL_MAIN_REZENCO_RATES_LIST) > 0) {
            try {
                String hotelId = (String) redisUtil.rightPop(RedisKeyConstant.HOTEL_MAIN_REZENCO_RATES_LIST);
                if (StringUtils.isBlank(hotelId)) {
                    continue;
                }
                Date start = new Date();
                Date end = DateUtils.addDays(start, days);
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                sourceInfos.forEach(htSourceInfo -> {
                    String groupId = (String) JsonUtil.toMap(htSourceInfo.getExtra()).get("groupId");
                    String companyId = (String) JsonUtil.toMap(htSourceInfo.getExtra()).get("companyId");
                    rezenTaskService.syncRezencoRatesTask(htSourceInfo.getSourceId(),htSourceInfo.getSourceAppId(),
                            htSourceInfo.getSourceSecret(), Long.valueOf(groupId),
                            rezenService.parseHotelId3(hotelId), Long.valueOf(companyId),
                            simpleDateFormat.format(start), simpleDateFormat.format(end));
                });
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
    }
}
